import {Action} from 'redux';

import immutableArray from '../common/immutableArray';
import {IDesign} from '../types/IDesign';
import {ActionType} from './ActionType';

export interface DesignIdsState extends Array<string> {
  [index: number]: string;
}

export interface DesignIdsAction extends Action {
  type: ActionType;
  designId?: string;
  design?: IDesign;
}

function designsReducer(state: DesignIdsState = [], action: DesignIdsAction): DesignIdsState {
  switch (action.type) {
    case ActionType.DESIGNS:
      return state;

    case ActionType.ADD_DESIGN:
      return immutableArray.add(state, action.design.id);

    case ActionType.REMOVE_DESIGN:
      return _removeDesign(state, action.designId);

    default:
      return state;
  }
}

function _removeDesign(state: DesignIdsState, designId: string): DesignIdsState {
  if (!designId) {
    return state;
  }

  // 查找设计所在的位置
  const designIndex = state.findIndex(item => {
    return item === designId;
  });

  if (designIndex === -1) {
    // 没找到
    return state;
  }

  return immutableArray.remove(state, designIndex);
}


export default designsReducer;
